var InUserManaged = function() {
	return {
		datatable : null,
		init : function() {
			this.initSearch();
			this.initListener();
		},
		initSearch : function() {
			if (!jQuery().dataTable) {
				return;
			}
			var uListTable = $("#userListTable").dataTable({
				"sAjaxSource" : ctx + "/incompanyUser/search?now=" + new Date().getTime(),
				"bSort":true,
				"aaSorting": [[ 1, "desc" ]],
				/* 使用post方式 */
				"fnServerData" : function(sSource, aoData, fnCallback) {
					var postData = {
						page : 1,start : 0,rows : 10,params : {},
						sortKey:"",
						sortOrder:""
					};
					
					var cols = ["index","ut.real_name","ut.user_name","ut.user_num","","ut.phone","ut.email","","","rt.name","",""];
					
					for(var i=0,sLen=aoData.length;i<sLen;i++){
						var aoC = aoData[i];
						if((aoC.name).indexOf("iSortCol")!=-1){
							postData.sortKey = cols[aoC.value];
						}else if((aoC.name).indexOf("sSortDir")!=-1){
							postData.sortOrder = aoC.value;
						}
					}
					
					if($('#searchUserName').val()){
						postData.params.userName = "%"+($('#searchUserName').val()).replace(/\s/g,"%")+"%";
					}
					
					if($('#searchUserNum').val()){
						postData.params.userNum = "%"+($('#searchUserNum').val()).replace(/\s/g,"%")+"%";
					}
					
					if($('#searchRealName').val()){
						postData.params.realName = "%"+($('#searchRealName').val()).replace(/\s/g,"%")+"%";
					}
					
					if($('#searchPhone').val()){
						postData.params.phone = "%"+($('#searchPhone').val()).replace(/\s/g,"%")+"%";
					}
					
					if($('#searchRole').val()){
						postData.params.role = ($('#searchRole').val()).replace(/\s/g,"%");
					}
					
					if($('#searchDisabled').val()){
						postData.params.disabled = ($('#searchDisabled').val()).replace(/\s/g,"%");
					}
					
					if($('#searchOfficeId').val()){
						postData.params.officeId = ($('#searchOfficeId').val()).replace(/\s/g,"%");
					}
					
					for (var i = 0, size = aoData.length; i < size; i++) {
						if (aoData[i].name == 'iDisplayLength') {
							postData.rows = aoData[i].value;
						} else if (aoData[i].name == 'iDisplayStart') {
							postData.start = aoData[i].value;
						} else if (aoData[i].name == 'sEcho') {
							postData.page = aoData[i].value;
						}
					}

					$.ajax({
						"dataType" : 'json',
						"cache": false,
						"type" : "POST",
						"url" : sSource,
						"data" : postData,
						"success" : function(data, textStatus, jqXHR){
							fnCallback(data.data, textStatus, jqXHR);
						}
					});
				},
				"bAutoWidth":false,
				"aoColumnDefs" : [
						
						{
							"data" : "index",
							"bSortable": false,
							"aTargets" : [ 0 ]
						},
						{
							"data" : "realName",
							"aTargets" : [ 1 ]
						},
						{
							"data" : "userName",
							"aTargets" : [ 2 ]
						},
						{
							"data" : "phone",
							"aTargets" : [ 3 ]
						},
						{
							"data" : "address",
							"bSortable": false,
							"aTargets" : [ 4 ]
						},
						{
							"data" : "officeName",
							"bSortable": false,
							"aTargets" : [ 5 ]
						},
						{
							"data" : "roleName",
							"aTargets" : [ 6 ]
						},
						{
							"aTargets" : [ 7 ],
							"bSortable": false,
							"mRender" : function(data, type, full) {
								return full.disabled==0?"启用":"禁用";
							}
						},
						{
							"aTargets" : [ 8 ],
							"bSortable": false,
							"mRender" : function(data, type, full) {
								var btns ='';
								btns +=  Permission.createPermElement('user:list:modify',' <button title="'+messages.public_button_edit+'" class="btn btn-sm-table  btn-primary" name="edit" target_id="'+full.id+'">编辑</button>');
								btns +=  Permission.createPermElement('user:list:modifypassword',' <button title="修改密码" class="btn btn-sm-table  btn-warning" name="editPassword" target_id="'+full.id+'">重置密码</button>');
								btns +=  Permission.createPermElement('user:list:del',' <button title="'+messages.public_button_del+'" class="btn btn-sm-table  btn-danger" name="del" target_id="'+full.id+'">删除</button>');
								
								return btns;
							}
						} ]
			});
			this.datatable = uListTable;
		},
		reSearch:function(){
        	this.datatable.fnDraw();
        },passwordLevel:function(password) {
        	var modes = [];
        	for (var i = 0; i < password.length; i++) {
        		idx = parseFloat(InUserManaged.charMode(password.charCodeAt(i)));
        		if(modes.length==0){
        			modes.push(idx);
        		}else{
        			var flags = false;
        			for(var j=0,slen=modes.length;j<slen;j++){
        				if(idx==modes[j]){
        					flags = true;
        				}
        			}
        			if(!flags){
        				modes.push(idx);
        			}
        		}
        	}
        	return modes;//如果不等于6,说明没有同时存在大小写和数字
        },charMode:function (iN) {
		    if(iN >= 48 && iN <= 57){
		    	return 1;
		    }//数字
		    if(iN >= 65 && iN <= 90){
		    	return 2;
		    } //大写字母
		    if(iN >= 97 && iN <= 122){
		    	return 3;
		    } //小写字母
		    return 0;
        },
		/**
		 * 监听开关事件
		 */
		initListener : function() {
			$("#searchBtn").click(function() {
				InUserManaged.reSearch();
				return false;
			});
			$("#clearBtn").click(function() {
				$("#searchForm")[0].reset();
				InUserManaged.reSearch();
				return false;
			});
			$("#addBtn").click(function() {
				InUserManaged.removeClass();
				$("div[name=actDlg] h4.modal-title").html("新增");
				$("#actForm")[0].reset();
				$("#actForm").find("input[name='id']").val("");
				$("#actDlg").modal("show");
			});
			
			
			$("#actFormBtn").click(function(){
				var form1 = $('#actForm');
				form1.validate({
					rules : {
						userName : {
							minlength :5,
							maxlength :25,
							required : true
						},
						realName : {
							maxlength :25,
							required : true
						},
						disabled : {
							required : true
						},
						officeId : {
							required : true
						},
						roleId : {
							required : true
						},
						phone : {
							maxlength :20
						},
						email : {
							maxlength :100,
							email : true
						},
						address : {
							maxlength :200
						}
					}
				});
				if(form1.valid()){
					var postData = $("form[name='actForm']").serializeJson();
					$.ajax({
						"dataType" : 'json',
						"cache": false,
						"type" : "POST",
						"data" : postData,
						"url" : ctx + "/incompanyUser/edit?now="+new Date().getTime(),
						"success" : function(data) {
							if(data.type==='success'){
								$("#actDlg").modal("hide");
								BootstrapDialog.show({
									title : messages.public_cue_cue,
									message : messages.public_cue_saveOk,
									buttons : [ {
										label : messages.public_cue_sure,
										cssClass : 'btn btn-sm btn-primary',
										action : function(dialogItself) {
											InUserManaged.reSearch();
											dialogItself.close();
										}
									} ]
								});
								
							}else{
								BootstrapDialog.show({
									type : BootstrapDialog.TYPE_WARNING,
									title : messages.public_cue_warning,
									message : data.message,
									buttons : [ {
										label : messages.public_cue_sure,
										cssClass : 'btn btn-sm btn-primary',
										action : function(dialogItself) {
											InUserManaged.reSearch();
											dialogItself.close();
										}
									} ]
								});
							}
						}
					});
				}
			});

			$("#editPasswordFormBtn").click(function(){
				var form1 = $('#editPasswordForm');
				form1.validate({
					rules : {
						password : {
							minlength : 5,
							required : true
						},
						repassword:{
							equalTo:'#password',
							minlength : 5,
							required : true
						}
					},
				   messages: {
			    	   repassword: {
						required: messages.system_user_inputconfirm_pwdtips,
			    	    minlength: messages.system_user_pwdless5_tips,
			    	    equalTo: messages.system_user_pwdtwice_notsame
			    	   }
				   },
				});
				if(form1.valid()){

					var postData = $("form[name='editPasswordForm']").serializeJson();
					$.ajax({
						"dataType" : 'json',
						"cache": false,
						"type" : "POST",
						"data" : postData,
						"url" : ctx + "/user/editPassword?now="+new Date().getTime(),
						"success" : function(data) {
							if(data.type=='success'){
								$("#editPasswordDlg").modal("hide");
								BootstrapDialog.show({
									type : BootstrapDialog.TYPE_WARNING,
									title : messages.public_cue_sure,
									message : messages.public_cue_saveOk,
									buttons : [ {
										label : messages.public_cue_sure,
										cssClass : 'btn btn-sm btn-primary',
										action : function(dialogItself) {
											InUserManaged.reSearch();
											dialogItself.close();
										}
									} ]
								});
								
							}else{
								BootstrapDialog.show({
									type : BootstrapDialog.TYPE_WARNING,
									title : messages.public_cue_warning,
									message : data.message,
									buttons : [ {
										label : messages.public_cue_sure,
										cssClass : 'btn btn-sm btn-primary',
										action : function(dialogItself) {
											dialogItself.close();
										}
									} ]
								});
							}
						}
					});
				}
			});
			
			/*
			 * 编辑
			 */
			$('#userListTable tbody').on('click', 'button[name="edit"]',function() {
				var id = $(this).attr("target_id");
				var form=$("form[name='actForm']");
				InUserManaged.removeClass();
				$.ajax({
					"dataType" : 'json',
					"type" : "POST",
					"cache" : false,
					"data" : {},
					"url" : ctx + '/user/get/'+id+'?now='+new Date().getTime(),
					"success" : function(data, textStatus, jqXHR){
						if (data.type == 'success') {
							$(form).binddata(data.data);
							$("div[name=actDlg] h4.modal-title").html("编辑");
							$("#actDlg").modal("show");
						} else {
							BootstrapDialog.show({
								title : messages.public_cue_message,
								message : data.message,
								buttons : [ {
									label : messages.public_cue_sure,
									action : function(dialog) {
										dialog.close();
									}
								} ]
							});
						}
					}
				});
			});
			$('#userListTable tbody').on('click', 'button[name="editPassword"]',function() {
				var id = $(this).attr("target_id");
				var form=$("form[name='editPasswordForm']");
				InUserManaged.removeClass();
				$.ajax({
					"dataType" : 'json',
					"cache": false,
					"type" : "POST",
					"data" : {},
					"url" : ctx + '/incompanyUser/get/'+id+'?now='+new Date().getTime(),
					"success" : function(data, textStatus, jqXHR){
						if (data.type == 'success') {
							$(form).find('input[name="id"]').val(data.data.id);
							$("div[name=editPasswordDlg] h4.modal-title").html("修改密码");
							$("#editPasswordDlg").modal("show");
						} else {
							BootstrapDialog.show({
								title : messages.public_cue_message,
								message : data.message,
								buttons : [ {
									label : messages.public_cue_sure,
									action : function(dialog) {
										dialog.close();
									}
								} ]
							});
						}
					}
				});
			});
			$('#userListTable tbody')
				.on('click', 'button[name="del"]',function() {
					var id = $(this).attr("target_id");
					InUserManaged.del(id);
				});
		},
		del : function(id) {
			BootstrapDialog.show({
				type : BootstrapDialog.TYPE_WARNING,
				title : messages.public_cue_warning,
				message : messages.public_cue_delSure,
				buttons : [ {
					label : messages.public_cue_close,
					cssClass: 'btn btn-sm btn-default',
					action : function(dialogItself) {
						dialogItself.close();
					}
				}, {
					label : messages.public_cue_sure,
					cssClass : 'btn btn-sm btn-primary',
					action : function(dialogItself) {
						InUserManaged.sureDel(id);
						dialogItself.close();
					}
				} ]
			});
		},
		sureDel : function(id){
			$.ajax({
				"dataType" : 'json',
				"cache": false,
				"type" : "POST",
				"data" : {},
				"url" : ctx + '/incompanyUser/delete/'+id+'?now='+new Date().getTime(),
				"success" : function(data, textStatus, jqXHR){
					if (data.type == 'success') {
						BootstrapDialog.show({
							title : messages.public_cue_message,
							message : messages.public_cue_delSuccess,
							buttons : [ {
								label : messages.public_cue_sure,
								action : function(dialog) {
									InUserManaged.reSearch();
									dialog.close();
								}
							} ]
						});
					} else {
						BootstrapDialog.show({
							title : messages.public_cue_message,
							message : data.message,
							buttons : [ {
								label : messages.public_cue_sure,
								action : function(dialog) {
									dialog.close();
								}
							} ]
						});
					}
				}
			});
		},removeClass:function(){
        	//去除Form表单的验证样式
        	$('.form-group','#editPasswordForm').removeClass('has-success').removeClass('has-error');
        	$('.form-group','#actForm').removeClass('has-success').removeClass('has-error');
    		 $('span').remove('.help-block');
        }
	};

}();